package com.hundsun.hsOffer.controller;

import com.hundsun.hsOffer.common.Constant;
import com.hundsun.hsOffer.model.CompanyFile;
import com.hundsun.hsOffer.model.OfferChannel;
import com.hundsun.hsOffer.model.OfferCompany;
import com.hundsun.hsOffer.utils.DataGrid;
import com.hundsun.hsOffer.utils.DateUtils;
import com.hundsun.hsOffer.utils.StringUtils;
import com.hundsun.hsOffer.utils.TreeNode;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;
import com.jfinal.upload.UploadFile;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Create By IDEA
 * User:giegie
 * Date:2016/8/11
 * Description: 报价系统业务控制器
 */
public class HsOfferController extends Controller {
    private Logger logger = Logger.getLogger(HsOfferController.class);

    /**
     * 第三方支付公司列表页面
     */
    public void companyListUI() {
        renderFreeMarker("companyList.ftl");
    }

    /**
     * 第三方支付公司列表
     */
    public void companyList() {
        DataGrid<OfferCompany> dataGrid = OfferCompany.dao.findByPage(getParaToInt("page"), getParaToInt("rows"));
        renderJson(dataGrid);
    }

    /**
     * 添加支付公司页面
     */
    public void addCompanyUI() {
        renderFreeMarker("companyAdd.ftl");
    }

    @Before(EvictInterceptor.class)
    @CacheName("nodes")
    public void addCompany() {
        String[] companyRanges = getParaValues("companyRange");
        OfferCompany company = getModel(OfferCompany.class, "", true);
        if (companyRanges != null && companyRanges.length >= 1) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < companyRanges.length - 1; i++) {
                sb.append(companyRanges[i] + ",");
            }
            sb.append(companyRanges[companyRanges.length - 1]);
            company.setCompanyRange(sb.toString());
        }
        company.setCreateTime(DateUtils.formatDate(new Date()));
        company.save();
        renderJson(true);
    }

    /**
     * 编辑支付公司页面
     */
    public void editCompanyUI() {
        Integer id = getParaToInt(0);
        OfferCompany company = OfferCompany.dao.findById(id);
        setAttr("company", company);
        renderFreeMarker("companyEdit.ftl");
    }

    @Before(EvictInterceptor.class)
    @CacheName("nodes")
    public void editCompany() {
        String[] companyRanges = getParaValues("companyRange");
        OfferCompany company = getModel(OfferCompany.class, "", true);
        if (companyRanges != null && companyRanges.length >= 1) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < companyRanges.length - 1; i++) {
                sb.append(companyRanges[i] + ",");
            }
            sb.append(companyRanges[companyRanges.length - 1]);
            company.setCompanyRange(sb.toString());
        }
        company.update();
        renderJson(true);
    }

    @Before(EvictInterceptor.class)
    @CacheName("nodes")
    public void delCompany() {
        Integer id = getParaToInt(0);
        OfferCompany company = OfferCompany.dao.findById(id);
        company.setDelFlag(Constant.DELETE);
        renderJson(company.update());
    }

    public void companyInfo() {
        Integer id = getParaToInt(0);
        OfferCompany company = OfferCompany.dao.findById(id);
        setAttr("company", company);
        renderFreeMarker("companyInfo.ftl");
    }

    /**
     * 支付公司支付方式展示列表
     */
    public void payTypeListUI() {
        renderFreeMarker("payTypeList.ftl");
    }

    @Before(CacheInterceptor.class)
    @CacheName("nodes")
    public void payTypeList() {
        //根部节点（一级节点）
        List<TreeNode> nodes = new ArrayList<TreeNode>();
        TreeNode node = new TreeNode();
        node.setId("0");
        node.setText("hs");
        node.setState("open");
        nodes.add(node);

        //查询全部的支付公司（二级节点）
        List<TreeNode> childrenNodes = OfferCompany.dao.findAll();
        node.setChildren(childrenNodes);
        renderJson(nodes);
    }

    /**
     * 支付渠道展示
     */
    public void payChannelListUI() {
        String channelId = getPara(0);
        setAttr("channelId", channelId);
        renderFreeMarker("payChannelList.ftl");
    }

    public void payChannelList() {
        String channelId = getPara(0);
        Integer page = getParaToInt("page");
        Integer rows = getParaToInt("rows");
        DataGrid<OfferChannel> dataGrid = OfferChannel.dao.findByPage(channelId, page, rows);
        renderJson(dataGrid);

    }


    public void addChannelUI() {
        String companyId = getPara(0);
        setAttr("companyId", companyId);
        renderFreeMarker("addChannel.ftl");
    }

    @Before(EvictInterceptor.class)
    @CacheName("nodes")
    public void addChannel() {
        OfferChannel channel = getModel(OfferChannel.class, "", true);
        channel.setCreateTime(DateUtils.formatDate(new Date()));
        renderJson(channel.save());
    }

    @Before(EvictInterceptor.class)
    @CacheName("nodes")
    public void delChannel() {
        int id = getParaToInt(0);
        renderJson(OfferChannel.dao.deleteById(id));
    }

    /**
     * 计算报价
     */
    public void countOfferUI() {
        renderFreeMarker("countOffer.ftl");
    }


    /**
     * 根据条件查询channel
     */
    public void searchChannel() {
        int page = getParaToInt("page");
        int rows = getParaToInt("rows");
        //获取查询条件
        String companyName = getPara("companyName");
        String payScene = getPara("payScene");
        String deviceName = getPara("deviceName");
        String type = getPara("type");
        String sort = getPara("sort");
        String order = getPara("order");

        DataGrid<Record> dataGrid = OfferChannel.dao.findByCondition(deviceName, payScene, type, sort, order, companyName, page, rows);
        renderJson(dataGrid);
    }

    /**
     * 添加预估值
     */
    public void countConditionUI() {
        String ids = getPara(0); //渠道ids
        setAttr("ids", ids);
        renderFreeMarker("countConditionAdd.ftl");
    }

    public void countCondition() {
        //int useType = getParaToInt("useType");//用户类型
        Long estimatedMoney = getParaToLong("estimatedMoney");  //交易金额
        Long estimatedValue = getParaToLong("estimatedValue"); //交易笔数
        String idsIn = getPara("ids");
        double sum = 0;
        if (StringUtils.isNotEmpty(idsIn) && StringUtils.isNoneBlank(idsIn)) {
            String stringIds[] = idsIn.split(",");
            for (String id : stringIds) { //根据id查询相关渠道信息
                OfferChannel channel = OfferChannel.dao.findById(Integer.parseInt(id));
                if (channel.getOfferType() == Constant.FIX_ANDAN) { //固定按单收费
                    String offerPrice = channel.getOfferPrice();
                    sum = sum + estimatedValue * Double.parseDouble(offerPrice);
                } else if (channel.getOfferType() == Constant.FIX_ANBILI) { //固定按比例收费
                    String offerPrice = channel.getOfferPrice();
                    sum = sum + estimatedMoney * Double.parseDouble(offerPrice);
                } else if (channel.getOfferType() == Constant.STEP_ANDAN) {//阶梯按单
                    // 获取阶梯值
                    String criticalValues[] = channel.getCriticalValue().split(",");
                    //获取阶梯对应报价
                    String offerPrices[] = channel.getOfferPrice().split(",");
                    for (int i = 0; i < criticalValues.length; i++) {
                        /**
                         *   A--B 介于 A-B之间
                         */
                        if (i + 1 < criticalValues.length && estimatedValue >= Long.parseLong(criticalValues[i]) && Long.parseLong(criticalValues[i + 1]) > estimatedValue) {//判断输入金额所在阶梯
                            String offerPrice = offerPrices[i + 1];
                            sum = sum + estimatedValue * Double.parseDouble(offerPrice);
                            break;
                        }

                        /**
                         *  大于B
                         */
                        if (i == criticalValues.length - 1 && estimatedValue >= Long.parseLong(criticalValues[i])) {
                            String offerPrice = offerPrices[i + 1];
                            sum = sum + estimatedValue * Double.parseDouble(offerPrice);
                            break;
                        }

                        /**
                         * 小于 A
                         */
                        if (estimatedValue < Long.parseLong(criticalValues[i])) {
                            String offerPrice = offerPrices[i];
                            sum = sum + estimatedValue * Double.parseDouble(offerPrice);
                            break;
                        }
                    }
                } else if (channel.getOfferType() == Constant.STEP_ANBILI) {//阶梯按比例
                    // 获取阶梯值
                    String criticalValues[] = channel.getCriticalValue().split(",");
                    //获取阶梯对应报价
                    String offerPrices[] = channel.getOfferPrice().split(",");
                    for (int i = 0; i < criticalValues.length; i++) {
                        /**
                         *   A--B 介于 A-B之间
                         */
                        if (i + 1 < criticalValues.length && estimatedMoney >= Long.parseLong(criticalValues[i]) && Long.parseLong(criticalValues[i + 1]) > estimatedMoney) {//判断输入金额所在阶梯
                            String offerPrice = offerPrices[i + 1];
                            sum = sum + estimatedMoney * Double.parseDouble(offerPrice);
                            break;
                        }
                        /**
                         *  大于B
                         */
                        if (i == criticalValues.length - 1 && estimatedMoney >= Long.parseLong(criticalValues[i])) {
                            String offerPrice = offerPrices[i + 1];
                            sum = sum + estimatedMoney * Double.parseDouble(offerPrice);
                            break;
                        }
                        /**
                         * 小于 A
                         */
                        if (estimatedMoney < Long.parseLong(criticalValues[i])) {
                            String offerPrice = offerPrices[i];
                            sum = sum + estimatedMoney * Double.parseDouble(offerPrice);
                            break;
                        }
                    }
                }
            }
        }
        renderJson(sum);
    }

    public void uploadfileUI() {
        Integer id = getParaToInt(0);
        setAttr("id", id);
        render("fileUpload.ftl");
    }

    public void uploadfile() {
        Integer id = getParaToInt(0);
        UploadFile uploadFile = getFile("Filedata");
        if (id != null && uploadFile != null) {
            String fileName = uploadFile.getOriginalFileName();
            CompanyFile company_file = CompanyFile.dao.findByFileName(fileName);
            if (company_file == null) {
                CompanyFile companyFile = new CompanyFile();
                companyFile.setCompanyId(id);
                companyFile.setFileName(uploadFile.getOriginalFileName());
                String date = DateUtils.getDate("yyyyMMdd");
                companyFile.setCreateTime(date);
                companyFile.setFileUrl(date + File.separator + uploadFile.getFileName());
                companyFile.save();
                renderJson("上传成功");
            } else {
                renderJson("上传失败，已存在同名文件");
            }
        } else {
            renderJson("上传失败");
        }
    }

    public void downloadFileUI() {
        Integer id = getParaToInt(0);
        if (id != null) {
            List<CompanyFile> files = CompanyFile.dao.findByCompanyId(id);
            setAttr("files", files);
        }
        render("downloadFile.ftl");
    }

    public void delFile() {
        Integer id = getParaToInt(0);
        if (id != null) {
            //删除表数据
            CompanyFile companyFile = CompanyFile.dao.findById(id);
            //删除文件
            if (companyFile != null) {
                companyFile.delete();
                //String filename =PathKit.getWebRootPath() + File.separator + "upload" +File.separator + companyFile.getFileName();
                String filename = "c:/upload" + File.separator + companyFile.getFileName();
                logger.info(filename);
                File file = new File(filename);
                file.delete();
                renderJson("删除成功,刷新即可");
            } else {
                renderJson("删除失败");
            }
        } else {
            renderJson("删除失败");
        }
    }

    public void companyChannelListUI(){
        Integer id = getParaToInt(0);
        setAttr("companyId",id);
        render("companyChannelList.ftl");
    }

    public void companyChannelList(){
        int page = getParaToInt("page");
        int rows = getParaToInt("rows");
        Integer companyId = getParaToInt(0);
        DataGrid<OfferChannel> dataGrid =  OfferChannel.dao.findPageByCompanyId(companyId,page,rows);
        renderJson(dataGrid);
    }
}
